//
//  WYTabBarItem.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/13.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

class WYTabBarItem: UITabBarItem {
    
    override var badgeValue: String? {
    
        didSet {
        
            let tabBarController = valueForKey("_target") as? UITabBarController
            
            for tabBarChild in (tabBarController?.tabBar.subviews)! {
            
                if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                    for UITabBarButtonChild in tabBarChild.subviews {
                    
                        if UITabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!) {
                        
                            for badgeViewChild in UITabBarButtonChild.subviews {
                            
                                if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
                                    //统计我们类里面有多少成员变量
                                    var count: UInt32 = 0
                                    //获取里面的成员列表
                                    let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground")!, &count)
                                    
                                    for  i in 0..<count {
                                        //获取指定位置的成员
                                        let ivar = ivars[Int(i)]
                                        //获取成员名字
                                        let name = ivar_getName(ivar)
                                        let type = ivar_getTypeEncoding(ivar)
                                        //把获取的成员名字转字符串
                                         print(name)
                                        let nameStr = String(CString: name, encoding: NSUTF8StringEncoding)
                                        let typeStr = String(CString: type, encoding: NSUTF8StringEncoding)
                                       
                                        print(nameStr)
                                        print(typeStr)
                                        //使用kvc 方式给我们_ image 成员变量赋值
                                        if nameStr == "_image" {
                                        
                                            badgeViewChild.setValue(UIImage(named: "main_badge"), forKey: "_image")
                                        }
                                        
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
}
